<template>
    <div class="base add-order-container">
        <HeaderTop title="Confirm Loan"></HeaderTop>
        <productSelect :pageTrackerInfo="pageTrackerInfo" v-model="form.productIds"/>
        <div class="payment">
            <div class="title">Payment method</div>
            <div class="channel border-top-icon form">
                <div class="form-group">
                    <label>Withdrawal Channel</label><!--取款银行-->
                    <input @focus="scrollIntoView('withdrawChannelName1')" ref="withdrawChannelName1"
                        v-model="form.withdrawChannelName1" @click="showChooseBank('channel1')" type="text"
                        :placeholder="$t('plsChoose')" readonly class="input-select val" />
                </div>
                <div class="form-group" v-if="form.withdrawChannel1 != 9 && form.withdrawChannel1 != 1">
                    <label>Withdrawal Account</label><!--取款银行-->
                    <input @click="handleWithdrawAccount" @focus="scrollIntoView('withdrawAccount1')" @blur="checkWithdrawAccount"
                        ref="withdrawAccount1" v-model="form.withdrawAccount1" type="text" :placeholder="$t('plsInput')"
                        class="val" />
                    <p class="error-tips-new">{{ $t('plsInputRightMobile') }}</p>
                </div>
            </div>
            <p class="tips">Tips:To guarantee to be credited successfully, please bind your own bank account.</p>
        </div>
        <div class="btn-box">
            <div class="agree">
                <div @click="() => isCheckAgree = !isCheckAgree" :class='{ "check-box": true, "checked": isCheckAgree }'>
                </div>
                <!--      <div class="privancy" @click="showPrivance=true"><span>I agree</span> agreement of Loan Service and Privancy</div>-->
                <div class="privancy" @click="showPrivance = true"><span>I have read and agree with</span> “Loan Agreement”
                </div>
            </div>
            <button class="submitBtn btn-ui" @click="submitHandler" :disabled="btnCanSubmit || disabledBtn">Confirm Loan</button>
        </div>

        <!--取款银行选择框-->
        <popup v-model="isVisibleBankPicker" position="bottom">
            <picker show-toolbar :title="$t('bank')" :columns="payChannelList" value-key="channelName"
                @cancel="isVisibleBankPicker = false" @confirm="chooseBank" />
        </popup>
        <privance v-model="showPrivance" @closePage="closePage"></privance>
    </div>
</template>
<script>
import privance from './components/privance';
// import succDialog from './components/succDialog';
// import feeDetails from './components/feeDetails';
import storage from '@/libs/storage';
import HeaderTop from '@/components/header-top';
import { validateMobile } from '@/libs/validate';
// import Hybrid from '@/components/uzone-hybrid';
import MixinValidateForm from '@/service/mixin-validate-form';
import { Popup, Picker, Dialog } from 'vant';
import productSelect from './components/productSelect'
import { mapState } from 'vuex'

export default {
    components: {
        Popup,
        Picker,
        Dialog,
        privance,
        HeaderTop,
        // feeDetails,
        productSelect
        // succDialog
    },
    mixins: [MixinValidateForm],
    data() {
        return {
            payChannelList: [],
            showPrivance: false,
            isCheckAgree: false,
            isVisibleBankPicker: false,
            channelType: '',
            form: {
                productIds: [],
                withdrawChannel1: null,
                withdrawAccount1: null,
                withdrawChannelName1: null,
            },
            // TODO 
            disabledBtn: false,
            pageTrackerInfo: {
                page: 'payInfo',
                startTime: new Date().getTime()
            }

        };
    },
    computed: {
        ...mapState({
            productOrderInfo: state => state.product.productOrderInfo
        }),

        btnCanSubmit() {
            let result = true;
            let form = this.form;
            if (this.isCheckAgree) {
                if (form.withdrawChannel1 == 9 || form.withdrawChannel2 == 1) {
                    result = false;
                } else {
                    if (form.withdrawAccount1 != '') {
                        result = false;
                    }
                };
            }
            return result;
        },
    },
    methods: {
        scrollIntoView(name) {
            const ua = navigator.userAgent;
            const isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1;
            if (isAndroid) {
                const dom = this.$refs[name];
                setTimeout(() => {
                    dom.scrollIntoView(true);
                    dom.scrollIntoViewIfNeeded();
                }, 300);
            }
        },
        submitHandler() {
            if (this.form.productIds.length == 0) {
                this.$toast('Please select product first');
                return
            }
            // const hybrid = new Hybrid(this.$os.android ? 'android' : 'ios');
            const me = this;
            let actionTime = Date.now() % 1000000000;
            // 本地开发测试使用
            if (process.env.NODE_ENV === 'development') {
                me.submint(actionTime);
                console.log('submitHandler: 开发环境模拟借款提交操作');
                return;
            };
            this.$hybrid.action('checkPermission', {
                action: actionTime,
                callback(data) {
                    if (data.status === 1) {
                        me.submint(actionTime);
                    }
                }
            });
        },
        submint(actionTime) {
            console.log(this.form.productIds)
            let eventValue = {}
            const product = this.productOrderInfo
            if (product.custApplyProductList) {
                const { name, amount } = product
                const list = product.custApplyProductList.filter(item => this.form.productIds.findIndex(item1 => item1.productId === item.productId) > -1).map(item => {
                    const { productId, contractAmount, productName } = item
                    return { productId, contractAmount, productName }
                })
                eventValue = {
                    name,
                    amount,
                    list
                }
            } else {
                const { productName, contractAmount, productId } = product
                eventValue = {
                    productName,
                    contractAmount,
                    productId
                }
            }
            if (this.form.withdrawChannel1 != 9 && this.form.withdrawChannel1 != 1) {
                if (!validateMobile(this.form.withdrawAccount1)) {
                    //this.$toast(this.$tc('plsInputRightMobile'));
                    this.markInputNew(["withdrawAccount1"]);
                    return;
                }
            };

            if (this.form.withdrawChannel2 != null) {
                //非线下
                if (this.form.withdrawChannel2 != 9 && this.form.withdrawChannel2 != 1) {
                    //无手机号码
                    if (this.form.withdrawAccount2 == null) {
                        this.$toast(this.$tc('plsInputMobile'));
                        return;
                    } else {
                        //有手机号码
                        //手机号码格式错误
                        if (!validateMobile(this.form.withdrawAccount2)) {
                            //  this.$toast(this.$tc('plsInputRightMobile'));
                            this.markInputNew(["withdrawAccount1"]);
                            return;
                        }
                    }
                }
            };
            let params = {
                productIds: this.form.productIds,
                contractAmount: this.activeAmount,
                channels: [
                    {
                        withdrawChannelName: this.form.withdrawChannelName1,
                        withdrawChannelCode: this.form.withdrawChannel1,
                        withdrawAccount: this.form.withdrawAccount1,
                    }
                    // {
                    //     withdrawChannelName:this.form.withdrawChannelName2,
                    //     withdrawChannelCode:this.form.withdrawChannel2,
                    //     withdrawAccount:this.form.withdrawAccount2,
                    // },
                ],
                action: actionTime
            };
            const fireToken = storage.get('fireToken')
            if (fireToken) params.appInstanceId = fireToken
            if (this.disabledBtn) return
            this.disabledBtn = true;
            // 银行卡信息页 - 提交 - 点击 - 【对应确认借款页】
            this.$buryPoint.action({
                eventName: 'payInfo_submit_click',
                eventValue,
                ...this.pageTrackerInfo
            });
            this.$api.createOrder(params).then(res => {
                let { status, error, data } = res;
                if (status == '1' && error == '00000000') {
                    this.orderNo = data;

                    console.log(data);
                    const afid = storage.get('afid') || null
                    const installTime = storage.get('installTime') || null
                    const deviceId = this.$storage.get('deviceId') || null
                    // 订单id是数组
                    const trackParams = {
                        appflyerId: afid,
                        installTime,
                        deviceId,
                        orderIdList: data
                    };
                    if (trackParams.appflyerId) {
                        this.$api.trackpointOrder(trackParams).then(() => {
                        }).catch((e) => {
                            console.log(e);
                        });
                    }
                    const productIds = this.form.productIds.map(item => item.productId)
                    this.$buryPoint.action({
                        eventName: 'payInfo_submit_success',
                        orderId: data.join(','),
                        eventValue,
                        productIds,
                        ...this.pageTrackerInfo
                    });
                    this.$router.replace({
                        path: "/addOrderOne/success",
                    });
                }
            }).catch(e => {
                this.disabledBtn = false
            });
        },
        closePage(infp) {
            if (infp.type == 'confirm') {
                this.isCheckAgree = true;
            }
            this.showPrivance = false;
        },
        handleWithdrawAccount () {
            // 确认借款页填写银行卡点击
            this.$buryPoint.action({
                eventName: 'payInfo_accountNo_click',
                ...this.pageTrackerInfo
            });
        },
        showChooseBank(type) {
            // 确认借款页取款渠道点击
            this.$buryPoint.action({
                eventName: 'payInfo_channel_click',
                ...this.pageTrackerInfo
            });
            this.channelType = type;
            this.isVisibleBankPicker = true;
        },
        // 获取本月前多少天
        getPreDay(preDay = 13) {
            const now = new Date();
            const nowTime = now.getTime();
            const days = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
            const endOfdays = new Date(now.getFullYear(), now.getMonth(), days, 23, 59, 59);
            const preDaysTime = new Date(endOfdays.getFullYear(), endOfdays.getMonth(), endOfdays.getDate() - preDay).getTime();
            return nowTime > preDaysTime;
        },
        chooseBank(val) {
            console.log(val);
            if (this.channelType == 'channel1') {
                this.form.withdrawChannel1 = val.channelCode;
                this.form.withdrawChannelName1 = val.channelName;
                this.form.withdrawAccount1 = null;
            };
            if (this.channelType == 'channel2') {
                this.form.withdrawChannel2 = val.channelCode;
                this.form.withdrawChannelName2 = val.channelName;
                this.form.withdrawAccount2 = null;

            };
            this.isVisibleBankPicker = false;
            if (val.channelName == 'Gcash' && this.getPreDay()) {
                Dialog.alert({
                    title: '',
                    confirmButtonColor: '#EC5958',
                    confirmButtonText: 'OK',
                    message: 'Please make sure that Gcash has enough available balance,otherwise the loan will fail. It is recommended to use other payment methods at the end of the month.',
                }).then(() => {
                    console.log('close');
                });
            }
        },
        queryPayChannel() {

            this.$api.queryPayChannel().then(res => {
                let { status, error, data } = res;
                if (status == 1 && error == '00000000' && data) {
                    this.payChannelList = res.data.payChannelList;
                };
            });
        },
        checkWithdrawAccount() {
            if (!validateMobile(this.form.withdrawAccount1)) {
                // this.$toast(this.$tc('plsInputRightMobile'));
                this.markInputNew(["withdrawAccount1"]);
                return;
            }
        }
    },
    beforeDestroy () {
        this.pageEndAction()
    },
    created() {
        this.queryPayChannel();
    },
};
</script>
<style lang="scss" scoped>
@import './index.scss';
// @import './assets/scss/partials/reset';</style>
